package scct.shixingyu.dao;

import scct.shixingyu.model.User;
import scct.shixingyu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public User login(String name, String pass) {
//        获取数据库链接
        User user = null;
        Connection conn = DBUtils.getConnection();
        String sql = "select  *  from   sm_user where  customername=?  and  password=?";

        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, pass);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                String customername = rs.getString("customername");
                String password = rs.getString("password");
                int age = rs.getInt("age");
                String gender = rs.getString("gender");
                String mobile = rs.getString("mobile");
                user = new User(id, customername, gender, mobile, password, age);
            }
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    public List<User> getAllUser() {
        Connection conn = DBUtils.getConnection();
        List<User> users = new ArrayList<>();
        String sql = "select*from sm_user ";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String customername = rs.getString("customername");
                String password = rs.getString("password");
                int age = rs.getInt("age");
                String gender = rs.getString("gender");
                String mobile = rs.getString("mobile");
                users.add(new User(id, customername, gender, mobile, password, age));

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return users;
    }

    public boolean addUser(String customername, String password, String gender,
                           int age, String mobile) {
//        添加是否成果的标志
        int result = 0;
        Connection conn = DBUtils.getConnection();
        String insert_sql = "insert into sm_user values(null,?,?,?,?,?)";
        try {
            PreparedStatement pstmt = conn.prepareStatement(insert_sql);
            pstmt.setString(1, customername);
            pstmt.setString(2, gender);
            pstmt.setString(3, mobile);
            pstmt.setInt(4, age);
            pstmt.setString(5, password);
            result = pstmt.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result == 1;

    }
}



